package edu.maping.easy.model;

import java.util.ArrayList;
import java.util.List;

import processing.core.PApplet;

public class World {

	public ArrayList<Thing> world = new ArrayList<Thing>();

	public int addPolygon(Thing physicPolyThing) {

		int index = world.size();

		world.add(physicPolyThing);

		return index;
	}

	public ArrayList<Thing> getWorld() {
		return world;
	}

	public void draw(PApplet pApplet) {
		for (int i = 0; i < world.size(); i++) {
			world.get(i).draw(pApplet);
		}
	}

	public void editDraw(PApplet pApplet) {

		for (int index = 0; index < world.size(); index++) {
			Thing thing = world.get(index);
			//pApplet.strokeWeight(10F);
			pApplet.stroke(0, 255, 0);
			thing.editDraw(pApplet);
		}
	}

	public List<Thing> findByRectangle(Point point, Point point2) {

		Point leftPoint = null;
		Point rigthPoint = null;

		Point topPoint = null;
		Point bottomPoint = null;

		if (point.x < point2.x) {
			leftPoint = point;
			rigthPoint = point2;
		} else {
			leftPoint = point2;
			rigthPoint = point;
		}

		if (point.y < point2.y) {
			bottomPoint = point;
			topPoint = point2;
		} else {
			bottomPoint = point2;
			topPoint = point;
		}

		List<Thing> things = new ArrayList<Thing>();
		for (int index = 0; index < world.size(); index++) {
			Thing thing = world.get(index);
			if (thing instanceof PolygonThing) {
				PolygonThing polygonThing = (PolygonThing) thing;
				for (int index2 = 0; index2 < polygonThing.vertex.size(); index2++) {
					Point point3 = polygonThing.vertex.get(index2);
					if (point3.x > leftPoint.x && point3.x < rigthPoint.x
							&& point3.y > bottomPoint.y
							&& point3.y < topPoint.y) {
						things.add(thing);
						break;
					}
				}
			}
		}
		return things;
	}

	public PolygonThing hovered(int x, int y) {

		Point point = new Point(x, y);

		for (Thing thing : world) {
			if (thing instanceof PolygonThing) {
				PolygonThing physicPolyThing = (PolygonThing) thing;
				if (physicPolyThing.contains(point)) {
					return physicPolyThing;
				}
			}
		}

		return null;
	}

	public Thing findById(long id) {
		for (int index = 0; index < world.size(); index++) {
			if (world.get(index).getId() == id) {
				return world.get(index);
			}
		}
		return null;
	}

}
